<template>
  <div>
    <div>华西二院耳鼻喉头颈外科睡眠呼吸监测预约系统</div>
    <van-form>
      <van-field
        v-model="patient_name"
        label="患儿姓名"
        required
        placeholder="请输入患儿姓名"
      ></van-field>
      <van-field
        v-model="patient_registration_number"
        label="患儿登记号（8位数）"
        type="number"
        required
        disabled
        placeholder="请输入患儿登记号"
      ></van-field>
      <van-field
        v-model="examination_date_text"
        label="检查日期"
        readonly
        clickable
        @click="showDatePicker = true"
        required
        placeholder="请选择检查日期"
      ></van-field>
      <van-field
        v-model="contact_phone"
        label="联系电话"
        type="number"
        required
        disabled
        placeholder="请输入联系电话"
      ></van-field>
      <!-- 使用flex布局将按钮居中显示 -->
      <div class="button-container">
        <van-button type="primary" @click="goBack">返回</van-button>
        <van-button type="primary" @click="goSubmit">提交预约</van-button>
      </div>
      <!-- 日期选择器弹出层 -->
      <van-popup v-model="showDatePicker" position="bottom">
        <van-datetime-picker
          v-model="examination_date"
          type="date"
          :min-date="minDate"
          :max-date="maxDate"
          @confirm="onConfirm"
          @cancel="showDatePicker = false"
        ></van-datetime-picker>
      </van-popup>
    </van-form>
  </div>
</template>

<script>

import { addMother } from '@/services/mother'
import { Notify } from 'vant'

export default {
  name: 'mother',
  data () {
    return {
      patient_name: '',
      patient_registration_number: '',
      examination_date: null, // 用于 v-model 绑定日期选择器的值
      examination_date_text: '', // 用于显示日期选择器的文本值
      contact_phone: '',
      showDatePicker: false, // 控制日期选择器弹出层的显示与隐藏
      minDate: new Date(), // 最小日期为今天
      maxDate: new Date(new Date().getTime() + 30 * 24 * 60 * 60 * 1000),
      timeRange: '13:00-17:00' // 固定的时间范围
    }
  },
  created () {
    if (this.$route.query.patient_registration_number) this.patient_registration_number = this.$route.query.patient_registration_number
    if (this.$route.query.contact_phone) this.contact_phone = this.$route.query.contact_phone
    this.setMinDateBasedOnCurrentTime()
  },
  methods: {
    setMinDateBasedOnCurrentTime () {
      const currentHour = new Date().getHours()
      if (currentHour >= 16) {
        // 如果当前时间已经超过或等于13点，设置最小日期为明天
        this.minDate = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + 1)
      } else {
        // 否则最小日期仍然是今天
        this.minDate = new Date()
      }
    },
    goBack () {
      this.$router.go(-1)
    },
    onConfirm (value) {
      const formattedDate = this.formatDate(value)
      this.examination_date_text = `${formattedDate} ${this.timeRange}` // 更新显示的文本值
      this.examination_date = formattedDate
      this.showDatePicker = false // 关闭弹出层
    },
    formatDate (date) {
      const year = date.getFullYear()
      const month = (1 + date.getMonth()).toString().padStart(2, '0') // 月份从0开始，所以需要+1，并使用padStart补0
      const day = date.getDate().toString().padStart(2, '0') // 使用padStart补0
      return `${year}-${month}-${day}`
    },
    async goSubmit () {
      if (!this.patient_name || !this.patient_registration_number || !this.examination_date_text || !this.contact_phone) {
        this.$toast.fail('请填写所有必填项')
        return
      }
      const response = await addMother({
        patientName: this.patient_name,
        patientRegistrationNumber: this.patient_registration_number,
        examinationDate: this.examination_date,
        contactPhone: this.contact_phone
      })
      if (response && response.data) {
        const code = response.data.code
        let message = ''
        switch (code) {
          case 200:
            message = '预约成功'
            Notify({
              type: 'success',
              message
            })
            await this.$router.push({
              name: 'mother_success',
              query: {
                patient_name: this.patient_name
              }
            })
            break
          case 100:
            message = '当天预约已满，请选择其他日期'
            Notify({
              type: 'danger',
              message
            })
            break
          case 300:
            message = '已过预约时间，请在16:00前预约'
            Notify({
              type: 'danger',
              message
            })
            break
          case 400:
            message = '该患儿和联系电话已有预约记录'
            Notify({
              type: 'danger',
              message
            })
            break
          default:
            message = '预约失败'
            Notify({
              type: 'danger',
              message
            })
        }
      } else {
        Notify({
          type: 'danger',
          message: '预约请求失败'
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.button-container {
  display: flex;
  justify-content: space-between; /* 使得按钮之间有空隙，并分别位于容器两侧 */
  margin-top: 10px; /* 您可以根据需要调整按钮与上方内容的间距 */
}
</style>
